package com.threeti.mecool.mobile.controller;

import static com.threeti.mecool.mobile.MessageConst.MSG_AUTH_005;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.threeti.mecool.core.domain.model.client.AndroidApk;
import com.threeti.mecool.core.infrastructure.persistence.client.AndroidApkRepository;
import com.threeti.mecool.mobile.Commander;
import com.threeti.mecool.mobile.interfaces.ResponserDto;
import com.threeti.mecool.mobile.interfaces.assembler.ClientBundleAssembler;
import com.threeti.mecool.mobile.interfaces.dto.AndroidApkDto;

@Controller
@RequestMapping(value = "/apk")
public class ApkMaintenanceMobiController {
  
  @Autowired
  private AndroidApkRepository apkRepo;

  @RequestMapping(value = "/latest")
  @ResponseBody
  public ResponserDto optLatest(@RequestParam(required = true) String imei, int currentClientApkVersion) throws Exception {
    String command = Commander.command();
    
    //TODO jay:手机IMEI码校验...
    if (false)
      return ResponserDto.withBizFailureMsg(command, MSG_AUTH_005);
    
    AndroidApk latestApk = apkRepo.findByLatestVersion();
    
    if (latestApk == null) {      
      return ResponserDto.successCommand(command).withBizSuccessBody("apklatest", new AndroidApkDto());
    }
    
    AndroidApkDto rtnDto = ClientBundleAssembler.toDto(latestApk);
    if (currentClientApkVersion < latestApk.getVersion()) {
      rtnDto.setOptUrl(latestApk.getUrl());
    } else {
      rtnDto.setOptUrl(null);
    }
    
    return ResponserDto.successCommand(command).withBizSuccessBody("apklatest", rtnDto);
  }
}
